use tauri::{Emitter, PhysicalPosition, WindowEvent};
use tauri::{AppHandle, Manager, Wry};
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons};
use tauri_plugin_store::StoreExt;
use serde_json::json;

pub fn close_dialog(app: &tauri::AppHandle<Wry>) {
    let main_window = app.get_webview_window("main").unwrap();
    let main_window_clone = main_window.clone();
    let win_app = app.clone();
    
    


    main_window.on_window_event(move |event| {
        if let WindowEvent::CloseRequested { api, .. } = event {
          println!(">>>>>>>>close window {:?}",event);
          let store = win_app.store_builder("store.bin").build();
          
          let value = store.get("main_window_close");
          if None == value {
            // 阻止默认的关闭行为
            api.prevent_close();
            let app_clone = win_app.clone();
            let answer = app_clone
                .dialog()
                .message("Are you sure you want to exit ?")
                .title("Confirm")
                .buttons(MessageDialogButtons::OkCancelCustom(
                    "Close".into(),
                    "Cancel".into(),
                ))
                .blocking_show();
            if answer {
              // println!("close window {}",answer);
              store.set("main_window_close", json!({ "close": 1 }));
              // let value = store.get("main_window_close");
              // println!("{:?}", value);
              let _ = store.save();
              // app_clone.exit(0);
                // 用户确认关闭，关闭窗口
                main_window_clone.close().unwrap();
                app_clone.exit(0);
                // let payload = true;
                // win_app.app_handle().emit("main_win_close", payload).unwrap();
            }
          }else {
            // println!("222222{:?}", value); 
            store.delete("main_window_close");
            let _ = store.save();

          }
          // match value {
          //     Some(v) => println!("====={:?}", v),
          //     None => println!("====={:?}", value),
          // }
        }
    });
}
